import os
import re
import base64
import time
import datetime
import json
from flask import (
    Blueprint, flash, g, redirect, render_template, request, url_for, send_from_directory, current_app, jsonify
)
from sqlalchemy import desc
from jinja2.filters import do_striptags
from werkzeug.utils import secure_filename
from garden import db
from garden.models import Repair,RepairReply,User,RepairLog
from garden.auth import login_required

ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

bp = Blueprint('repair', __name__)


statusDic = {'00':'待确认','01':'已确认', '02':'处理中','03':'处理完成','04':'已解决'}

@bp.route('/repairs')
@bp.route('/repairs/<int:page>')
def list_repairs(page=1):
	if g.user == None:
		g.user = User.query.get(1000)

	repairs = Repair.query.all()
	paginate = Repair.query.order_by(desc('urgency')).order_by(desc('pub_time')).filter_by(cmnt_id = g.user.cmnt_id).filter_by(del_flag = 0).paginate(page,5,False)
	return render_template('repair/repairs.html',repairs=paginate.items)

@bp.route('/loadRepairs/<int:page>')
def load_repairs(page):
	if g.user == None:
		g.user = User.query.get(1000)

	paginate = Repair.query.order_by(desc('urgency')).order_by(desc('pub_time')).filter_by(cmnt_id = g.user.cmnt_id).filter_by(del_flag = 0).paginate(page,5,False)
	repairs=paginate.items
	repairList = []

	if repairs:
		for repair in repairs:
			repairList.append({'id':repair.id,'status':repair.status,'urgency':repair.urgency,'title':repair.title,'content':do_striptags(repair.content),'pub_time':repair.pub_time.strftime('%Y-%m-%d %H:%M:%S')})
	return jsonify({"repairs":repairList})

@bp.route('/newRepair')
@login_required
def newRepair():
	return render_template('repair/post.html')

@bp.route('/pubRepair',methods=['POST'])
@login_required
def pub_repair():
	title = request.form['title']
	content = request.form['content']
	urgency = int(request.form['urgency'])

	print('title is %s;  content is %s;  urgency is %d' %  (title,content,urgency))

	if title and content :
		# repair = Repair(title=title,content=content,category='00',tags=None,publisher=g.user.id,pub_time=datetime.datetime.now(),cmnt_id=1001)
		property_staff = User.query.filter_by(cmnt_id=g.user.cmnt_id).filter(User.roles.ilike('%,1002,%')).all()
		opid = 1001
		if property_staff:
			opid = property_staff[0].id

		repair = Repair(title=title ,content=content ,publisher_id=g.user.id ,pub_time=datetime.datetime.now() ,cmnt_id=g.user.cmnt_id ,status='00' ,urgency=urgency ,operator_id=opid ,modify_time =datetime.datetime.now())
		db.session.add(repair)
		db.session.commit()
	return render_template('repair/msg.html')

@bp.route('/showRepair/<int:rpr_id>')
def show_repair(rpr_id):
	repair = Repair.query.get(rpr_id)
	# print(repair.logs)
	if repair :
		property_staff = User.query.filter_by(cmnt_id=repair.cmnt_id).filter(User.roles.ilike('%,1002,%')).all()

		return render_template('repair/repair.html',repair=repair, staff=property_staff)
	else:
		return render_template('error.html',msg={'title':'系统错误','message':'报修信息不存在'})

@bp.route('/postRepairReply',methods=['POST'])
@login_required
def post_reply():
	data = request.get_data()
	json_data = json.loads(data.decode("utf-8"))

	reply = RepairReply(content=json_data.get('content'),rpr_id=json_data.get('rprId'), publisher_id=g.user.id, pub_time=datetime.datetime.now())
	db.session.add(reply)
	db.session.commit()
	replies = RepairReply.query.filter_by(rpr_id=json_data.get('rprId'))
	replyList = []
	for reply in replies:
		u = reply.publisher
		r = {'id':reply.id,'content':reply.content,'publisher_id':reply.publisher_id,'pub_time':reply.pub_time.strftime('%Y-%m-%d %H:%M:%S'),'publisher':{'nickname':u.nickname,'avatar':u.avatar}}
		replyList.append(r)

	return jsonify({"replies":replyList})

@bp.route('/changeOperator',methods=['POST'])
@login_required
def change_operator():
	data = request.get_data()
	json_data = json.loads(data.decode("utf-8"))
	repair = Repair.query.get(json_data.get('rprId'))

	if repair:
		print(repair.operator.nickname)
		repair.operator_id = json_data.get('operator_id')
		operator = User.query.get(json_data.get('operator_id'))
		print(repair.operator.nickname)
		logContent = "经办人：%s --> %s " % (repair.operator.nickname,operator.nickname)
		log = RepairLog(content=logContent,rpr_id=repair.id, changer_id=g.user.id,pub_time=datetime.datetime.now())
		db.session.add(log)
		db.session.commit()
		db.session.add(repair)
		db.session.commit()
		

		return jsonify({"success":True,"operator":{"nickname":operator.nickname}})
	else:
		return jsonify({"success":False})

@bp.route('/handleRepair',methods=['POST'])
@login_required
def handle_repair():
	data = request.get_data()
	json_data = json.loads(data.decode("utf-8"))
	op = json_data.get('op')
	repair = Repair.query.get(json_data.get('rprId'))

	if 'confirm' == op:
		logContent = "状态：%s --> %s " % (statusDic[repair.status],statusDic['01'])
		log = RepairLog(content=logContent,rpr_id=repair.id, changer_id=g.user.id,pub_time=datetime.datetime.now())
		db.session.add(log)
		db.session.commit()
		repair.status = '01'
		db.session.add(repair)

		db.session.commit()

		return jsonify({"success":True})
	elif 'handle' == op:
		logContent = "状态：%s --> %s " % (statusDic[repair.status],statusDic['02'])
		log = RepairLog(content=logContent,rpr_id=repair.id, changer_id=g.user.id,pub_time=datetime.datetime.now())
		db.session.add(log)
		db.session.commit()
		repair.status = '02'
		db.session.add(repair)
		db.session.commit()
		return jsonify({"success":True})

	elif 'complete' == op:
		logContent = "状态：%s --> %s " % (statusDic[repair.status],statusDic['03'])
		log = RepairLog(content=logContent,rpr_id=repair.id, changer_id=g.user.id,pub_time=datetime.datetime.now())
		db.session.add(log)
		db.session.commit()
		#问题完成时 将经办人改为 发起人
		repair.status = '03'
		repair.operator_id = repair.publisher_id
		db.session.add(repair)
		db.session.commit()
		return jsonify({"success":True})

	elif 'close' == op:
		logContent = "状态：%s --> %s " % (statusDic[repair.status],statusDic['04'])
		log = RepairLog(content=logContent,rpr_id=repair.id, changer_id=g.user.id,pub_time=datetime.datetime.now())
		db.session.add(log)
		db.session.commit()
		repair.status = '04'
		db.session.add(repair)
		db.session.commit()
		return jsonify({"success":True})

	elif 'reopen' == op:
		logContent = "状态：%s --> %s " % (statusDic[repair.status],statusDic['02'])
		log = RepairLog(content=logContent,rpr_id=repair.id, changer_id=g.user.id,pub_time=datetime.datetime.now())
		db.session.add(log)
		db.session.commit()
		#重新打开问题时 经办人改为物业管理员
		staff = User.query.filter_by(cmnt_id=repair.cmnt_id).filter(User.roles.ilike('%,1003,%'))
		if staff:
			repair.operator_id = staff[0].id
		repair.status = '02'
		db.session.add(repair)
		db.session.commit()
		return jsonify({"success":True})

	else:
		return jsonify({"success":False})

	if repair:
		repair.operator_id = json_data.get('operator_id')
		db.session.add(repair)
		db.session.commit()
		operator = User.query.get(json_data.get('operator_id'))

		return jsonify({"success":True,"operator":{"nickname":operator.nickname}})
	else:
		return jsonify({"success":False})